const { MongoClient, ObjectId } = require('mongodb');
const fs = require('fs');
const path = require('path');
const AdmZip = require('adm-zip');
const uri = "mongodb://hj:207131@47.98.220.209:27017/jinbeibei?authSource=admin"; // 替换为你的连接字符串
const dbName = "jinbeibei";
const outputDir = path.join(__dirname, 'backup_output');
const compressToZip = true;

// 将文档中的 ObjectId 转换为 Extended JSON 格式（用于保留类型）
function serialize(doc) {
    for (let key in doc) {
        if (doc[key] instanceof ObjectId) {
            doc[key] = { "$oid": doc[key].toString() };
        }
    }
    return doc;
}

async function exportDatabase() {
    const client = new MongoClient(uri, {
        // useNewUrlParser: true,
        // useUnifiedTopology: true,
    });

    try {
        await client.connect();
        console.log("✅ 成功连接到 MongoDB");

        const db = client.db(dbName);
        const collections = await db.listCollections().toArray();

        if (!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir, { recursive: true });
        }

        for (const coll of collections) {
            const collectionName = coll.name;
            console.log(`导出集合: ${collectionName}`);

            const cursor = db.collection(collectionName).find({});
            const docs = await cursor.toArray();

            const serializedDocs = docs.map(serialize);

            const filePath = path.join(outputDir, `${collectionName}.json`);
            fs.writeFileSync(filePath, JSON.stringify(serializedDocs, null, 2), 'utf-8');
            console.log(`✅ 已保存至 ${filePath}`);
        }

        if (compressToZip) {
            const zipFileName = `KF_${new Date().toISOString().slice(0, 10)}.zip`;
            const zip = new AdmZip();
            zip.addLocalFolder(outputDir);
            zip.writeZip(path.join(__dirname, zipFileName));
            console.log(`📦 已打包为 ${zipFileName}`);
        }

        console.log("🎉 数据库导出完成！");
    } catch (err) {
        console.error("❌ 导出失败:", err.message);
    } finally {
        await client.close();
    }
}

exportDatabase();
